package com.ych.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ych.beans.Message;
import com.ych.beans.UserManager;
import com.ych.dao.UserDao;
import com.ych.service.UserService;
import com.ych.util.SessionNameEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao dao;

    @Autowired
    StringRedisTemplate temp;

    @Override
    public Message selectUser(Integer pageNo, String key, Integer user_id) {
        Message message = new Message();
        if(pageNo!=null){
            PageHelper.startPage(pageNo, 8);
        }
        List<UserManager> list=dao.selectUser(key,user_id,null);
        PageInfo<UserManager> objectPageInfo = new PageInfo<>(list);
        message.setSuccess(true);
        if(!list.isEmpty()){
            if (user_id == null) {
                message.setObj(objectPageInfo);
            }else {
                message.setObj(list.get(0));
                message.setMsg("查询成功");
            }
        }
        return message;
    }

    @Override
    public Message addUser(UserManager userManager) {
        Message message = new Message();
        boolean flag = dao.addUser(userManager);
        message.setSuccess(flag);
        if (flag){
            message.setMsg("用户添加成功");
        }else {
            message.setMsg("用户添加失败");
        }
        return message;
    }

    @Override
    public Message deleteUser(Integer id) {
        Message message = new Message();
        boolean flag = dao.deleteUser(id);
        message.setSuccess(flag);
        if (flag){
            message.setMsg("删除成功");
        }else {
            message.setMsg("删除失败");
        }
        return message;
    }

    @Override
    public Message login(UserManager userManager, HttpSession session) {
        Message message = new Message();
        boolean isSuccess = true;
        UserManager userSql = null;
        String msg = "登录成功";
        final List<UserManager> userList = dao.selectUser(null, null,userManager.getUsername());
        if (userList.isEmpty()){
            isSuccess = false;
            msg = "用户名不存在";
        }else {
            userSql = userList.get(0);
            if (!userSql.getPassword().equals(userManager.getPassword())){
                isSuccess = false;
                msg = "密码错误";
                userSql = null;
            }
        }
        //登录成功就加入redis缓存
        if (isSuccess){
            temp.opsForHash().put(SessionNameEnum.LOGIN.getName(), session.getId(), JSON.toJSONString(userSql));
        }
        message.setSuccess(isSuccess);
        message.setMsg(msg);
        message.setObj(userSql);
        return message;
    }
}
